import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/group_history_res.dart';
import 'package:mall/core/models/group_purchase_status.dart';
import 'package:mall/core/services/api.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'components/fake_dropdown_button.dart';
import 'group_port_screen.dart';

/// 拼购历史
class GroupHistoryScreen extends StatefulWidget {
  static const routeName = "/GroupHistoryScreen";

  @override
  _GroupHistoryScreenState createState() => _GroupHistoryScreenState();
}

class _GroupHistoryScreenState extends State<GroupHistoryScreen> {
  String _error;

  // 年度条件
  List<dynamic> _years;
  String _year;

  // 拼购状态条件
  List<MapEntry<String, dynamic>> _statuses;
  MapEntry<String, dynamic> _status;

  // 拼购子账号Id条件
  List<MapEntry<String, dynamic>> _ports;
  MapEntry<String, dynamic> _port;

  // 列表
  RefreshController _refreshController;
  int _pageIndex;
  List<GroupHistoryRes> _currentList;
  final List<GroupHistoryRes> _list = [];

  @override
  void initState() {
    super.initState();
    _fetchParams();
    _refreshController = RefreshController();
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("拼购历史"),
      ),
      body: _error == null && _years == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _years == null
              ? Center(
                  child: Text("$_error"),
                )
              : _buildBody(),
    );
  }

  Widget _buildBody() {
    return Column(
      children: [
        _buildHeader(),
        Expanded(
          child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: _currentList?.length == 10,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.separated(
              padding: EdgeInsets.symmetric(vertical: 8.w),
              itemBuilder: (context, index) => _buildItem(_list[index]),
              separatorBuilder: (context, index) => SizedBox(height: 8.w),
              itemCount: _list.length,
            ),
          ),
        ),
      ],
    );
  }

  Padding _buildHeader() {
    return Padding(
      padding: EdgeInsets.all(8.w),
      child: Row(
        children: [
          Expanded(
            child: FakeDropdownButton(
              text: "${_year ?? "所有年度"}",
              onPressed: _showYearSheet,
            ),
          ),
          SizedBox(width: 4.w),
          Expanded(
            child: FakeDropdownButton(
              text: "${_status?.value ?? "全部状态"}",
              onPressed: _showStatusSheet,
            ),
          ),
          SizedBox(width: 4.w),
          Expanded(
            child: FakeDropdownButton(
              text: "${_port?.value ?? "全部账户"}",
              onPressed: _showPortSheet,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildItem(GroupHistoryRes res) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.all(8.w),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "${res.portName}",
                    style: TextStyle(color: Colors.black),
                  ),
                  Text(
                    "${res.deliveryStatus ?? '--'}",
                    style: TextStyle(fontSize: 12.sp),
                  ),
                ],
              ),
              SizedBox(height: 8.w),
              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(4.w),
                    child: ImageNetwork(url: "${res.productPicture}", width: 40.w, height: 40.w),
                  ),
                  SizedBox(width: 8.w),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("${res.productName}"),
                      SizedBox(height: 4.w),
                      Text(
                        "${res.disburseUnit} ${res.disburse} x1",
                        style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 14.sp),
                      ),
                    ],
                  )
                ],
              ),
              SizedBox(height: 8.w),
              Text("订单 ${res.orderCode ?? '--'}", style: TextStyle(fontSize: 10.sp)),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "拼购时间 ${res.createTime}",
                    style: TextStyle(fontSize: 10.sp),
                  ),
                  SizedBox(
                    height: 22.w,
                    child: OutlineButton(
                      onPressed: () => _onTapAgain(res),
                      borderSide: BorderSide(color: Theme.of(context).primaryColor),
                      child: Text('再来一单'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        // 标签
        _buildTag(res),
      ],
    );
  }

  Widget _buildTag(GroupHistoryRes res) {
    switch (res.status) {
      case GroupPurchaseStatus.IN_PIN_GOU:
        // 拼购中
        return Positioned(
          top: 20.w,
          right: 105.w,
          child: Image.asset('assets/image/group_ing.png', width: 70.w, height: 70.w),
        );
      case GroupPurchaseStatus.PIN_GOU_FAIL:
        // 已退券
        return Positioned(
          top: 20.w,
          right: 105.w,
          child: Image.asset('assets/image/group_return.png', width: 70.w, height: 70.w),
        );
      case GroupPurchaseStatus.PIN_GOU_SUCCESS:
        // 拼成功
        return Positioned(
          top: 20.w,
          right: 105.w,
          child: Image.asset('assets/image/group_success.png', width: 70.w, height: 70.w),
        );
      case GroupPurchaseStatus.PIN_GOU_TIMEOUT:
        // 已超时
        return Positioned(
          top: 20.w,
          right: 105.w,
          child: Image.asset('assets/image/group_expired.png', width: 70.w, height: 70.w),
        );
      default:
        return Container();
    }
  }

  /// 年份
  void _showYearSheet() async {
    final year = await showModalBottomSheet(
      context: context,
      builder: (context) => ListView.builder(
        shrinkWrap: true,
        itemBuilder: (context, index) => ListTile(
          title: Text("${_years[index]}"),
          onTap: () => Navigator.of(context).pop(_years[index]),
        ),
        itemCount: _years.length,
      ),
    );
    if (year == null) {
      return;
    }
    setState(() {
      _year = year;
    });
    _refreshController.requestRefresh();
  }

  /// 状态
  void _showStatusSheet() async {
    final status = await showModalBottomSheet(
      context: context,
      builder: (context) => ListView.builder(
        shrinkWrap: true,
        itemBuilder: (context, index) => ListTile(
          title: Text("${_statuses[index].value}"),
          onTap: () => Navigator.of(context).pop(_statuses[index]),
        ),
        itemCount: _statuses.length,
      ),
    );
    if (status == null) {
      return;
    }
    setState(() {
      _status = status;
    });
    _refreshController.requestRefresh();
  }

  /// 账户
  void _showPortSheet() async {
    final port = await showModalBottomSheet(
      context: context,
      builder: (context) => ListView.builder(
        shrinkWrap: true,
        itemBuilder: (context, index) => ListTile(
          title: Text("${_ports[index].value}"),
          onTap: () => Navigator.of(context).pop(_ports[index]),
        ),
        itemCount: _ports.length,
      ),
    );
    if (port == null) {
      return;
    }
    setState(() {
      _port = port;
    });
    _refreshController.requestRefresh();
  }

  /// 拉取参数
  void _fetchParams() async {
    final api = context.read<Api>();
    try {
      final years = await api.groupPurchaseHistoryParamYear("EJL_PG");
      final statuses = await api.groupPurchaseHistoryParamStatus("EJL_PG");
      final ports = await api.groupPurchaseHistoryParamPort("EJL_PG");
      if (!mounted) {
        return;
      }
      setState(() {
        _years = years;
        _statuses = statuses.entries.toList();
        _ports = ports.entries.toList();
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    } catch (e) {
      debugPrint("$e");
    }
    // 参数拉取完成后，刷新一次数据
    _onRefresh();
  }

  /// 第一页
  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final list = await api.groupPurchaseHistory(_year, _status?.key, _port?.key, _pageIndex);
      if (!mounted) {
        return;
      }
      _refreshController.refreshCompleted();
      setState(() {
        _currentList = list;
        _list.clear();
        _list.addAll(list);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 更多页
  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final list = await api.groupPurchaseHistory(_year, _status?.key, _port?.key, _pageIndex);
      if (!mounted) {
        return;
      }
      _refreshController.loadComplete();
      setState(() {
        _currentList = list;
        _list.addAll(list);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.loadFailed();
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 点击再来一单
  void _onTapAgain(GroupHistoryRes res) {
    Navigator.of(context).pushNamed(
      GroupPortScreen.routeName,
      arguments: GroupPortScreenArgs(res.modelInAreaId, res.productPicture),
    );
  }
}
